﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TrainingsApp.Logic.Import.Model;
using System.IO;

namespace TrainingsApp.Logic.Import.Template {
    public class Txt_ChapterDataReader_1 : ITemplateReader {
        public Dictionary<int, object> ReadAll(int keyId, string location, int templateType) {
            Dictionary<int, object> temp = new Dictionary<int, object>();
            ChapterTemplate_1 root = new ChapterTemplate_1();
            root.Name = "Root";

            ChapterTemplate_1 tempEntity = root;

            string line = string.Empty;
            int bfLevel = 0;
            int level = 0;
            int tempLevel = 0;
            using (FileStream fStream = new FileStream(location, FileMode.Open, FileAccess.Read)) {
                using (StreamReader reader = new StreamReader(fStream, Encoding.UTF8)) {
                    root.Name = reader.ReadLine();
                    var tempArr = root.Name.Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries);
                    root.Name = tempArr[1];
                    root.MetalsId = Convert.ToInt32(tempArr[0]);
                    while (reader.Peek() != -1) {
                        line = reader.ReadLine();
                        if (string.IsNullOrEmpty(line)) continue;

                        if (!line.StartsWith("\t")) {
                            level = 0;
                        }
                        else if (line.StartsWith("\t\t\t")) {
                            level = 3;
                        }
                        else if (line.StartsWith("\t\t")) {
                            level = 2;
                        }
                        else if (line.StartsWith("\t")) {
                            level = 1;
                        }
                        else {
                            continue;
                        }
                        tempLevel = level;
                        while (tempLevel != bfLevel) {
                            if (tempLevel < bfLevel) {
                                tempEntity = tempEntity.Parent;
                                bfLevel--;
                            }
                            else {
                                tempEntity = tempEntity.Children.LastOrDefault();
                                bfLevel++;
                            }
                        }
                        if (tempEntity != null) {
                            tempEntity.Children.Add(new ChapterTemplate_1 {
                                Name = line.Replace("\t", ""),
                                Parent = tempEntity
                            });
                        }
                    }
                }
            }



            temp.Add(1, root);
            return temp;
        }






    }
}
